package petertel.pbx.conf.logger;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.StringReader;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.StringTokenizer;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import petertel.pbx.conf.ConfigItem;
import petertel.pbx.conf.GenericConfigWriter;
import petertel.pbx.connector.Executor;
import petertel.pbx.utils.ParserUtils;

public class LoggerConfBase extends ConfigItem<Logfile> {

	public void parse(Executor executor) {
		final Pattern LOGFILE = Pattern.compile("^\\s*([^;\\s]+)\\s*=>(.*)$");
		children = new ArrayList<Logfile>();
		String content = ParserUtils.readFile(executor,
				"/etc/asterisk/logger.conf");
		BufferedReader breader = new BufferedReader(new StringReader(content));
		int lineno = 0;
		String currentSection = null;
		try {
			for (;;) {
				String line = breader.readLine();
				if (line == null) {
					break;
				}
				lineno++;
				if (ParserUtils.isSection(line)) {
					currentSection = ParserUtils.getSectionName(line);
				} else if (currentSection == null) {
					;
				} else if (currentSection.equals("logfiles")) {
					Matcher logfileMatcher = LOGFILE.matcher(line);
					if (logfileMatcher.matches()) {
						Logfile logfile = new Logfile();
						String logfilename = logfileMatcher.group(1);
						String levels = logfileMatcher.group(2);
						logfile.setFilename(logfilename);
						logfile.setLineno(lineno);
						StringTokenizer tokenizer = new StringTokenizer(
								levels.trim(), ",");
						Set<Loglevel.Type> selectedType = new HashSet<Loglevel.Type>();
						while (tokenizer.hasMoreTokens()) {
							String level = tokenizer.nextToken().trim();
							selectedType.add(Loglevel.Type.valueOf(level));
						}
						List<Loglevel> list = logfile.getLoglevels();
						for (Loglevel loglevel : list) {
							if (selectedType.contains(loglevel.getType())) {
								loglevel.setChecked(true);
							}
						}
						children.add(logfile);
					} else {
						;
					}
				} else {
					;
				}
			}
		} catch (IOException e) {
			throw new RuntimeException(e);
		}
	}

	@Override
	public String write() {
		return null;
	}

	@Override
	public String toString() {
		String ret = "";
		for (int i = 0; i < children.size(); i++) {
			ret += children.get(i);
		}
		return ret;
	}

}
